import { getToken } from '@/utils/auth'

// API基础URL配置
const getBaseUrl = () => {
  // 开发环境使用代理，返回空字符串，让请求通过 vite 代理转发
  // 这样可以避免浏览器的 CORS 跨域问题
  if (process.env.NODE_ENV === 'development') {
    return ''
  }
  
  // 生产环境使用环境变量或默认地址
  return process.env.VUE_APP_BASE_API || 'http://47.106.144.160'
}

const BASE_URL = getBaseUrl()
const TIMEOUT = 10000

/**
 * 请求拦截器
 */
const requestInterceptor = (config) => {
  // 准备请求头，整合默认请求头和自定义请求头
  const header = {
    'Content-Type': 'application/json',
    'channel': '10000',
    'appId': '1',
    ...config.header
  }

  // 从本地存储获取token并添加到请求头
  const token = getToken()

  if (token) {
    header.token = token
    console.log(`[Request Interceptor] 成功为请求 ${config.url} 添加了Token。`)
  } else {
    console.warn(`[Request Interceptor] 未在缓存中找到Token，请求 ${config.url} 将不带Token。`)
  }
  
  // 将最终的headers赋值给config
  config.header = header
  
  // 设置基础URL
  if (!config.url.startsWith('http')) {
    config.url = BASE_URL + config.url
  }
  
  // 设置超时时间
  config.timeout = config.timeout || TIMEOUT
  
  // 为POST、PUT、DELETE请求的body添加统一参数
  if (['POST', 'PUT', 'DELETE'].includes(config.method?.toUpperCase()) && config.data) {
    config.data = {
      appId: 1,
      channel: 10001,
      ...config.data
    }
  }
  
  // 为GET请求添加查询参数
  if (config.method?.toUpperCase() === 'GET' && config.data) {
    config.data = {
      appId: 1,
      channel: 10001,
      ...config.data
    }
  }
  
  return config
}

/**
 * 响应拦截器
 */
const responseInterceptor = (response) => {
  const { data } = response
  
  // 统一处理响应数据
  if (data.code === 0) {
    return data
  } else {
    // 显示错误信息
    uni.showToast({
      title: data.msg || '请求失败',
      icon: 'none'
    })
    return Promise.reject(new Error(data.msg || '请求失败'))
  }
}

/**
 * 错误处理
 */
const errorHandler = (error) => {
  console.error('请求错误:', error)
  
  let message = '网络错误'
  if (error.message) {
    message = error.message
  } else if (error.statusCode) {
    switch (error.statusCode) {
      case 400:
        message = '请求参数错误'
        break
      case 401:
        message = '未授权，请重新登录'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求地址不存在'
        break
      case 500:
        message = '服务器内部错误'
        break
      default:
        message = `请求失败: ${error.statusCode}`
    }
  }
  
  uni.showToast({
    title: message,
    icon: 'none'
  })
  
  return Promise.reject(error)
}

/**
 * 通用请求方法
 */
export const request = (options) => {
  return new Promise((resolve, reject) => {
    // 应用请求拦截器
    const config = requestInterceptor(options)
    
    uni.request({
      ...config,
      success: (response) => {
        try {
          const result = responseInterceptor(response)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        errorHandler(error)
        reject(error)
      }
    })
  })
}

/**
 * GET请求
 */
export const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

/**
 * POST请求
 */
export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

/**
 * PUT请求
 */
export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

/**
 * DELETE请求
 */
export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

/**
 * 文件上传
 */
export const upload = (url, filePath, options = {}) => {
  return new Promise((resolve, reject) => {
    const token = getToken()
    const headers = {
      'Content-Type': 'multipart/form-data',
      'channel': '10000',
      'appId': '1'
    }
    
    if (token) {
      headers.token = token
    }
    
    // 构建formData，添加统一参数
    const formData = {
      appId: 1,
      channel: 10001,
      ...options.formData
    }
    
    uni.uploadFile({
      url: BASE_URL + url,
      filePath,
      name: 'file',
      header: headers,
      formData: formData,
      ...options,
      success: (response) => {
        try {
          const data = JSON.parse(response.data)
          const result = responseInterceptor({ data })
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        errorHandler(error)
        reject(error)
      }
    })
  })
}

/**
 * 文件下载
 */
export const download = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    const token = getToken()
    const headers = {
      'channel': '10000',
      'appId': '1'
    }
    
    if (token) {
      headers.token = token
    }
    
    uni.downloadFile({
      url: BASE_URL + url,
      header: headers,
      ...options,
      success: (response) => {
        if (response.statusCode === 200) {
          resolve(response)
        } else {
          reject(new Error('下载失败'))
        }
      },
      fail: (error) => {
        errorHandler(error)
        reject(error)
      }
    })
  })
}

export default {
  request,
  get,
  post,
  put,
  del,
  upload,
  download
} 